let App = getApp();

Page({
  data: {
    list: [],
    default_id:null,
  },

  user_id: 10001,
  onLoad: function (options) {
    // 当前页面参数
    this.data.options = options;
  },

  onShow: function () {
    // 获取收货地址列表
    this.getCouponList();
  },

  setDefault: function (e) {
    let _this = this,
      address_id = e.detail.value;
    _this.setData({
      default_id: parseInt(address_id)
    });

      _this.data.options.from === 'flow' && wx.navigateBack();
   
    return false;
  },
  /**
   * 获取收货地址列表
   */
  getCouponList: function () {
    let _this = this;
    let data = {
      list: [],
    }

    App._get('couponUser/lists', {}, function (result) {
      data = _this.initData(result.data);

      _this.setData({
        list: data
      });
    });
  },

  initData(datas) {
    console.log("数据", datas);
    for (let i in datas){
    datas[i].coupon.start_time = App.timeformat2(datas[i].coupon.start_time);
    datas[i].coupon.erffective_time = App.timeformat2(datas[i].coupon.erffective_time);

    }
    return datas;
  },


  /**
   * 添加新地址
   */
  createAddress: function () {
    wx.navigateTo({
      url: './create'
    });
  },

  /**
   * 编辑地址
   */
  editAddress: function (e) {
    wx.navigateTo({
      url: "./detail?address_id=" + e.currentTarget.dataset.id
    });
  },

  /**
   * 移除收货地址
   */
  removeAddress: function (e) {
    let _this = this,
      address_id = e.currentTarget.dataset.id;
    wx.showModal({
      title: "提示",
      content: "您确定要移除当前收货地址吗?",
      success: function (o) {
        o.confirm && App._post_form('address/delete', {
          address_id: address_id,
          user_id: 10001
        }, function (result) {
          _this.getAddressList();
        });
      }
    });
  },

  /**
   * 设置为默认地址
   */
  setDefault: function (e) {
    let _this = this,
      address_id = e.detail.value;
    _this.setData({
      default_id: parseInt(address_id)
    });
    
    App._get('couponUser/' + address_id, {   }, function (result) {
      let coupon = result.data;
      if (_this.data.options.from === 'flow'){
        var pages = getCurrentPages();
        var currPage = pages[pages.length - 1];   //当前页面
        var prevPage = pages[pages.length - 2];  //上一个页面
        prevPage.setData({
          coupon:coupon
        })
       
        wx.navigateBack({ delta: 1 });
      }
       
    });
    return false;
  },

});